<?php
/**
 * Created by PhpStorm.
 * User: HLG
 * Date: 2019/10/16
 * Time: 14:01
 */
namespace app\api\model;
use app\common\model\UploadFile;
use think\Request;
use think\Db;
class Order extends BaseModel
{
    protected $table = 'content_order';
    protected $goodsSku;
    protected $orderGoods;
    protected $user;
    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->goodsSku = new GoodSku();
        $this->orderGoods = new OrderGoods();
        $this->user = new User();
    }

    /**
     * 矿工挂卖
     *
     * @param $postData
     * @param $order_sn
     * @param $total_price
     * @param $user_id
     * @return bool
     */
    public function saleOrder($user_id)
    {
        $data = input('post.');
        if($data['num']<=0 || empty($data['num'])){
            AjaxReturn(0,'挂卖数量不能小于1个');
        }
        if(empty($data['price'])){
            AjaxReturn(0,'请输入售卖价格');
        }
        if(empty($data['payment_id'])){
            AjaxReturn(0,'请选择收款方式');
        }
        //检查剩余资产
        $checkNum = $this->checkNum($user_id,abs($data['num']));
        if(!$checkNum){
            $status = ['code'=>0,'msg'=>'剩余矿工数量不足'];
        }else{
            $order_sn = date('YmdHis'). rand(10000000,99999999).$user_id;
            $total = $data['num'] * $data['price'];
            $insertData = [
                'ordernum' => $order_sn,
                'seller' => $user_id,
                'num' => abs($data['num']),
                'price' => $data['price'],
                'z_price' => $total,
                'pay_type' => $data['pay_type'],
                'status' => 0,
                'type' => 2,
                'create_time' => time(),
                'payment_id' => $data['payment_id'],
            ];
            $this->startTrans();
            $insertOrder = $this->insertInfo($insertData);
            $balanceModel = new Balance();
            $balanceRes = $balanceModel->changeBalance($user_id,'absenteeism',$data['num'],2,4,'矿工挂卖');
            if($insertOrder && $balanceRes){
                $this->commit();
                $status = ['code'=>1,'msg'=>'挂卖成功'];
            }else{
                $this->rollback();
                $status = ['code'=>0,'msg'=>'挂卖失败'];
            }
        }
        return $status;
    }

    /**
     * 订单挂买
     *
     * @param $user_id
     * @return array
     */
    public function buyOrder($user_id)
    {
        $data = input('post.');
        if($data['num']<=0 || empty($data['num'])){
            AjaxReturn(0,'数量不能小于1个');
        }
        if(empty($data['price'])){
            AjaxReturn(0,'请输入收购价格');
        }
        $order_sn = date('YmdHis'). rand(10000000,99999999).$user_id;
        $total = $data['num'] * $data['price'];
        $insertData = [
            'ordernum' => $order_sn,
            'seller' => $user_id,
            'num' => intval($data['num']),
            'price' => $data['price'],
            'z_price' => $total,
            'pay_type' => '',
            'status' => 0,
            'type' => 1,
            'create_time' => time(),
        ];
        $insertOrder = $this->insertInfo($insertData);
        if($insertOrder){
            $status = ['code'=>1,'msg'=>'挂买成功'];
        }else{
            $status = ['code'=>0,'msg'=>'挂买失败'];
        }
        return $status;
    }

    /**
     * 查看订单详情
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderInfo($user_id)
    {
        $id = input('id');
        $data = $this->alias('o')->field('o.*,u.uname')->join('content_user u','u.id=o.seller')->where(['o.id'=>$id])->find();
        if($data){
            $status = ['code'=>1,'msg'=>'查询成功','data'=>$data];
        }else{
            $status = ['code'=>0,'msg'=>'订单不存在','data'=>''];
        }
        return $status;
    }

    /**
     * 查看订单列表
     *
     * @param $user_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderList($user_id)
    {
        $data = input('post.');
        $list = $this->alias('o')
            ->field('o.*,u.uname')
            ->join('content_user u','u.id=o.seller')
            ->where(['type'=>$data['type']])
            ->page($data['page'],10)
            ->select();
        if($list){
            $status = ['code'=>1,'msg'=>'查询成功','data'=>$list];
        }else{
            $status = ['code'=>0,'msg'=>'暂无订单','data'=>''];
        }
        return $status;
    }

    /**
     * 卖单购买
     * @param $user_id
     */
    public function purchase($user_id)
    {
        $data = input('post.');
        if(empty($data['buy_img'])){
            AjaxReturn(0,'请上传支付凭证');
        }else{
            $buy_img = upload();
            $updateOrderState = $this->updateInfo(['id'=>$data['id']],['status'=>1,'buy_img'=>$buy_img,'buyer'=>$user_id]);
            if($updateOrderState){
                AjaxReturn(1,'提交成功');
            }else{
                AjaxReturn(0,'提交失败');
            }
        }
    }

    /**
     * 卖单卖出
     *
     * @param $user_id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function sell($user_id)
    {
        $data = input('post.');
        $orderNum = $this->where(['id'=>$data['id']])->value('num');
        $checkNum = $this->checkNum($user_id,$orderNum);
        if(!$checkNum){
            AjaxReturn(0,'剩余矿工数量不足');
        }else{
            $this->startTrans();
            $result = $this->updateInfo(['id'=>$data['id']],['buyer'=>$user_id,'payment_id'=>$data['payment_id'],'state'=>1]);
            $balanceModel = new Balance();
            $balanceRes = $balanceModel->changeBalance($user_id,'absenteeism',$orderNum,2,4,'矿工卖出');
            if($result && $balanceRes){
                $this->commit();
                AjaxReturn(1,'卖出成功，请等待买家支付');
            }else{
                $this->rollback();
                AjaxReturn(0,'操作失败，请重试');
            }
        }

    }

    /**
     * 卖单撤回
     *
     * @param $user_id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function saleOrderCancle($user_id)
    {
        $id = input('post.id');
        //查询订单
        $orderInfo = $this->getInfo(['id'=>$id]);
        if($orderInfo['status']<2){
            $this->startTrans();
            //判断卖家是否是该用户
            if($orderInfo['type']==1){ //如果是挂买单
                if($orderInfo['buyer'] == $user_id){ //判断接单人是否为该用户
                    $balanceModel = new Balance();
                    $result = $balanceModel->changeBalance($user_id,'absenteeism',$orderInfo['num'],1,5,'撤回卖单');
                    $updateOrderState = $this->updateInfo(['id'=>$id],['status'=>4]);
                }else{
                    AjaxReturn(0,'您无法撤回该订单');
                }
            }else{ //如果是挂卖单
                if($orderInfo['seller'] == $user_id){//判断挂单人是否为该用户
                    $balanceModel = new Balance();
                    $result = $balanceModel->changeBalance($user_id,'absenteeism',$orderInfo['num'],1,5,'撤回卖单');
                    $updateOrderState = $this->updateInfo(['id'=>$id],['status'=>4]);
                }else{
                    AjaxReturn(0,'您无法撤回该订单');
                }
            }
            if($result && $updateOrderState){
                $this->commit();
                AjaxReturn(1,'撤回成功');
            }else{
                $this->rollback();
                AjaxReturn(0,'撤回失败');
            }
        }else{
            AjaxReturn(0,'已付款或已完成订单无法撤回');
        }
    }

    /**
     * 挂买单撤回
     *
     * @param $user_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buyOrderCancle($user_id)
    {
        $id = input('post.id');
        $orderInfo = $this->where(['id'=>$id,'seller'=>$user_id])->where('status','<',2)->find();
        if(!empty($orderInfo)){
            $result = $this->updateInfo(['id'=>$id,'seller'=>$user_id],['status'=>4]);
            if($result){
                AjaxReturn(1,'撤回成功');
            }else{
                AjaxReturn(1,'撤回失败');
            }
        }else{
            AjaxReturn(0,'您无法撤回该订单');
        }
    }
    /**
     * 检查余额是否足够
     *
     * @param $user_id
     * @param $num
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkNum($user_id,$num)
    {
        $balanceModel = new Balance();
        $balance = $balanceModel->getBalance($user_id);
        if($balance['absenteeism']>=$num){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 我的订单
     *
     * @param $user_id
     */
    public function myOrder($user_id)
    {
        $data = input('post.');
        switch ($data['type']){
            case 1: //我的买单
                $orderList = $this->getPageList(['seller'=>$user_id,'type'=>1],'',$data['page'],10);
                break;
            case 2:
                $orderList = $this->getPageList(['seller'=>$user_id,'type'=>2],'',$data['page'],10);
                break;
            case 3:
                $orderList = $this->getPageList(['seller|buyer'=>$user_id,'status'=>['<',3]],'',$data['page'],10);
                break;
            case 4:
                $orderList = $this->getPageList(['seller|buyer'=>$user_id,'status'=>3],'',$data['page'],10);
                break;
        }
        if(!empty($orderList)){
            AjaxReturn(1,'查询成功',$orderList);
        }else{
            AjaxReturn(0,'暂无订单','');
        }
    }
}